//
//  RJWarningTypeSection.m
//  AirQuality
//
//  Created by Po on 15/4/9.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJWarningTypeSection.h"

@interface RJWarningTypeSection ()

@property (retain, nonatomic) UIButton * currentButton;


- (void)initInterfaceWithTitles:(NSArray *)titles;
@end

@implementation RJWarningTypeSection

- (instancetype)initWithFrame:(CGRect)frame titles:(NSArray *)titiles
{
    self = [super initWithFrame:frame];
    if (self) {
        _currentPage = 0;
        [self initInterfaceWithTitles:titiles];
    }
    return self;
}

- (void)initInterfaceWithTitles:(NSArray *)titles
{
    [self setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"homeTableCellBack"]]];
    
    CGFloat width = self.frame.size.width / titles.count;
    NSUInteger count = 0;
    for (NSString * title in titles) {
        UIButton * button = [self createButtonWithFrame:CGRectMake(width * count, 0, width, self.frame.size.height) Title:title];
        [self addSubview:button];
        if (count == 0) {
            [button setSelected:YES];
            _currentButton = button;
//            [self getSelectBgWithFrame:button.frame];
            [self changeSelectBgFrame:button.frame];
        }
        [button setTag:300 + count];
        count ++;
    }
//    [self addSubview:_selectBg];
}

//- (UIImageView *)getSelectBgWithFrame:(CGRect)frame
//{
//    if(!_selectBg) {
//        _selectBg = [[UIImageView alloc] initWithFrame:frame];
//        [_selectBg setImage:[UIImage imageNamed:@"warningSectionGrass"]];
//    }
//    return _selectBg;
//}

- (UIButton *)createButtonWithFrame:(CGRect)frame Title:(NSString *)title
{
    UIButton * button = [[UIButton alloc] initWithFrame:frame];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [button setBackgroundImage:[UIImage imageNamed:@"warningSectionNormal"] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"warningSectionBack"] forState:UIControlStateSelected];
    
    [button addTarget:self action:@selector(pressButton:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

#pragma mark - function
- (void)changeSelectBgFrame:(CGRect)frame
{
    CGRect rect = frame;
    rect.origin.x = rect.origin.x + (rect.size.width - rect.size.width / 4);
    rect.origin.y = rect.size.height / 2;
    rect.size.width /= 4;
    rect.size.height /= 2;
//    [_selectBg setFrame:rect];
}

#pragma mark - event
- (void)pressButton:(UIButton *)button
{
    if (_currentButton == button) {
        return;
    }
    [_currentButton setSelected:NO];
    _currentButton = button;
    [_currentButton setSelected:YES];
    [self changeSelectBgFrame:button.frame];
    _currentPage = button.tag - 300;
    if (_delegate) {
        [_delegate WarningTypeSection:self didSelectCount:_currentPage];
    }
}
@end
